var formatTime = require("../components/fotmatTime.js");
var number = require("../components/number.js");
var $eachRate, $eachFeeNum, $eachMoney, $vCodeButton, $userId, $userPhone;
var idRegExp = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/;
var getVerifyCodeDJS = 60;
var returnUrl;
// 设置订单信息
function setOrderInfo(infoData) {
    if (infoData.simplPC == "1") {
        hideHeaderFoot();
    }
    $("#order-money").text(infoData.amount);
    $("#merName").text(infoData.merName);
    $("#orderNum").text(infoData.orderId);
    $("#payDate").text(infoData.tradeDate);
    returnUrl = infoData.returnUrl;
}

// 隐藏页头页尾
function hideHeaderFoot() {
    $(".wrapper>.page_header").hide();
    $(".wrapper>.footer").hide();
    $(".primary >.area_label>span").hide();
}

// 设置费率
function setRate(RateInfo) {
    var eachRate = number.hold2bit(parseFloat(RateInfo.rate) / parseFloat(RateInfo.nper));
    $eachRate.text(eachRate);
    $eachFeeNum.text(RateInfo.poundage);
    $eachMoney.text(RateInfo.eachamount);
}

// 设置期数
function setSelect(rateList,nper,unalter,amount) { // rateList 费率数组 、nper默认期数、unalter、不可改变,amount 分期金额
    var optionHtml = '';
    var amount = parseFloat(amount);
    if (unalter.search("nper") != -1 && nper) {
        for (var i = 0, l = rateList.length; i < l; i++) { // 上一版后台是amtLowLimit
            if (amount >= parseFloat(rateList[i].amtLowlimit) && amount <= parseFloat(rateList[i].amtUplimit) && rateList[i].nper == nper) {
                optionHtml += `<option value="${rateList[i].nper}">${rateList[i].nper}期</option>`;
            }
        }
    } else {
        for (var i = 0, l = rateList.length; i < l; i++) {
            if (amount >= parseFloat(rateList[i].amtLowlimit) && amount <= parseFloat(rateList[i].amtUplimit)) {  // 上一版后台是amtLowLimit
                optionHtml += `<option value="${rateList[i].nper}">${rateList[i].nper}期</option>`;
            }
        }
    }
    if(optionHtml ==''){
        $('#tsmodal .modal-body').text('没有可选期数');
        $('#tsmodal').modal('show');
    }


    $("#rateSelect").html(optionHtml);
    if (nper) {
        $("#rateSelect option[value=" + nper + "]").attr("selected", true);
    }
}

// 跳到第二步
function toFillUserInfo() {
    $("#countBox").hide();
    $("#cardInfo").show();
    $(".circle:eq(1)").addClass("checked");
}

// 跳到支付结果
function toResult() {
    $("#cardInfo").hide();
    $("#resultBox").show();
    $(".circle:eq(2)").addClass("checked");
    countDown();
}

// input 获得焦点
function infoFocusFuc() {
    var $theFormat = $(this).next("div.input-format");
    $theFormat.show();
}

// input 失去焦点隐藏提示
function infoInputBlur() {
    var $theFormat = $(this).next("div.input-format");
    $theFormat.hide();
}

// creditCardFormat 输入实时格式化提示
function creditCardFormat() {
    var thisVal = $("#xykNo").val();
    thisVal = thisVal.replace(/\D/g, "");
    $("#xykNo").val(thisVal);
    var $theFormat = $("#xykNo").next("div.input-format");
    if (thisVal.length < 4) {
        $theFormat.text(thisVal);
    } else if (thisVal.length > 4 && thisVal.length < 8) {
        $theFormat.text(thisVal.replace(/(\d{4})/, "$1  "));
    } else if (thisVal.length > 8 && thisVal.length < 12) {
        $theFormat.text(thisVal.replace(/(\d{4})(\d{4})/, "$1  $2  "));
    } else if (thisVal.length > 12) {
        $theFormat.text(thisVal.replace(/(\d{4})(\d{4})(\d{4})/, "$1  $2  $3  "));
    }

}

// 身份证格式提示
function userIdFormat() {
    var thisVal = $(this).val();
    thisVal = thisVal.replace(/[^0-9|X|x]/g, "");
    thisVal = thisVal.replace("x", "X");

    var $theFormat = $(this).next("div.input-format");
    if (thisVal.length < 6) {
        $theFormat.text(thisVal);
    } else if (thisVal.length > 6 && thisVal.length < 14) {
        $theFormat.text(thisVal.replace(/(\d{6})/, "$1  "));
    } else if (thisVal.length > 14) {
        $theFormat.text(thisVal.replace(/(\d{6})(\d{8})/, "$1  $2  "));
    }

    var isfrz = idRegExp.test(thisVal);
    var phoneValue = $userPhone.val();
    if (phoneValue.length == 11 && isfrz) {
        $vCodeButton.addClass("btn-ok");
    } else {
        $vCodeButton.removeClass("btn-ok");
    }
}



// 手机格式化提示
function userPhoneFormat() {
    var thisVal = $(this).val();
    thisVal = thisVal.replace(/\D/g, "");

    var $theFormat = $(this).next("div.input-format");
    if (thisVal.length < 3) {
        $theFormat.text(thisVal);
    } else if (thisVal.length > 3 && thisVal.length < 7) {
        $theFormat.text(thisVal.replace(/(\d{3})/, "$1  "));
    } else if (thisVal.length > 8) {
        $theFormat.text(thisVal.replace(/(\d{3})(\d{4})/, "$1  $2  "));
    }
    var frIdVal = $userId.val();
    var isfrz = idRegExp.test(frIdVal);
    if (thisVal.length == 11 && isfrz) {
        $vCodeButton.addClass("btn-ok");
    } else {
        $vCodeButton.removeClass("btn-ok");
    }
}

//  有效期格式提示
function dateFormat() {
    var thisVal = $(this).val();
    thisVal = thisVal.replace(/\D/g, "");
    var $theFormat = $(this).next("div.input-format");
    if (thisVal == "") {
        $theFormat.text("04/18 请输入了0418");
    } else if (thisVal.length == 4) {
        $theFormat.text(thisVal.replace(/(\d{2})(\d{2})/, "20$2年$1月"));
    }
}

// 格式化cvn2
function numberFormat() {
    var thisVal = $(this).val();
    thisVal = thisVal.replace(/\D/g, "");

}



// 设置默认数据和只读
function setReadOnly(infoData) {
    var readVal = infoData.unalter;
    var readIvalA = [{
        name: "custName",
        value: "userName",
        readonly: "creditName"
    }, {
        name: "cetitype",
        value: "",
        readonly: "cetitype"
    }, {
        name: "credCardno",
        value: "creditCard",
        readonly: "creditNo"
    }, {
        name: "xykNo",
        value: "xykNo",
        readonly: "creditNo"
    }, {
        name: "idno",
        value: "userId",
        readonly: "idno"
    }, {
        name: "hpno",
        value: "userPhone",
        readonly: "phoneNo"
    }, {
        name: "cvv",
        value: "cvn2",
        readonly: "cvv"
    }, {
        name: "vaPerd",
        value: "dateInput",
        readonly: "validty_period"
    }];
    for (var i = 0, l = readIvalA.length; i < l; i++) {
        if (infoData[readIvalA[i].name]) {
            $("#" + readIvalA[i].value).val(infoData[readIvalA[i].name]);

            if (readVal.search(readIvalA[i].readonly) != -1) {
                $("#" + readIvalA[i].value).attr("readonly", "readonly");
                $("#" + readIvalA[i].value).addClass("readonly");
            }
        }

    }
}

// 重置输入框
function resetInput() {
    $("#cardInfo input[readonly!='readonly']").val("");
}

// 验证是否可以取验证码
function canGetCode() {
    var frIdVal = $userId.val();
    var isfrz = idRegExp.test(frIdVal);
    var phoneNo = $userPhone.val();
    if (isfrz) {
        if (phoneNo.length == 11) {
            if (getVerifyCodeDJS == 60) {
                $vCodeButton.addClass("btn-ok");
            } else {
                $vCodeButton.removeClass("btn-ok");
            }

        } else {
            $vCodeButton.removeClass("btn-ok");
            $('#tsmodal .modal-body').text("手机号码错误");
            $('#tsmodal').modal('show');
        }

    } else {
        $vCodeButton.removeClass("btn-ok");
        $('#tsmodal .modal-body').text("身份证号码错误");
        $('#tsmodal').modal('show');
    }
}


//请求 验证码
function getVerifyCode(_params) {
    canGetCode();
    if ($vCodeButton.hasClass("btn-ok")) { //发送短信 禁用60秒

        //发送短信
        // 禁用60秒
        $vCodeButton.removeClass("btn-ok");
        $vCodeButton.text("重新获取(" + getVerifyCodeDJS + "S)");

        var setIntervarHandle = setInterval(function() {
            getVerifyCodeDJS--;
            $vCodeButton.text("重新获取(" + getVerifyCodeDJS + "s)");
            if (getVerifyCodeDJS == 0) {
                $vCodeButton.text("重新获取");
                clearInterval(setIntervarHandle);
                $vCodeButton.addClass("btn-ok");
                getVerifyCodeDJS = 60;
            };
        }, 1000);

        getVerificationCode(_params);
    }
}


// 发送验证码请求
function getVerificationCode(_params) {
    var url = LFQ_SMS_SEND_URL;
    var hp_no = $userPhone.val().replace(/ /g, "");
    var id_no = $userId.val().replace(/ /g, "");
    _params.hp_no = hp_no;
    _params.idno = id_no;
    $.post(url, _params, function(retn) {

        /*if (retn.code == "0" && retn.msg) {
            pview.showErroPrompt(retn.msg);
        }*/
    });
}

// 到计时 30 分钟后跳转到订单失效页面
function countDownTime() {
    var oldTime = (new Date()).getTime();
    var countDownhadle = setInterval(function() {
        var newTime = (new Date()).getTime();
        if (newTime - oldTime > 1790000) {
            clearInterval(countDownhadle);
            location.href = "../payInstallment/payPrompt.html?msg=该笔订单已失效，请重新下单";
        }
    }, 1000);
}

// 倒计时
function countDown() {
    var count = 10;
    if (returnUrl) {
        var theHandle = setInterval(function() {
            count--;
            $("#sjs>span").text(count);
            if (count == 0) {
                clearInterval(theHandle);
                location.href = returnUrl;

            }
        }, 1000);
    } else {
        $("#sjs").hide();
        $("#link-mall").parent().hide();
    }
}

//  设置分期交易时间
function setAgreeDate() {
    if ($("#agreeInput").attr("checked")) {
        var theDate = new Date();
        var agreeMonth = theDate.getMonth()+1>9?theDate.getMonth()+1:'0'+(theDate.getMonth()+1)
        var agreeDate = theDate.getDate()
        $("#agreeYear").text(theDate.getFullYear());
        $("#agreeMonth").text(agreeMonth);
        $("#agreeDate").text(agreeDate);
    } else {
        $("#agreeYear").text(" ");
        $("#agreeMonth").text(" ");
        $("#agreeDate").text(" ");
    }
}

// 初始化变量
function initView() {
    $eachRate = $("#eachRate");
    $eachFeeNum = $("#eachFeeNum");
    $eachMoney = $("#eachMoney");
    $vCodeButton = $("#vCodeButton");
    $userId = $("#userId");
    $userPhone = $("#userPhone");
    $("#cardInfo input").on("focus", infoFocusFuc);
    $("#cardInfo input").on("blur", infoInputBlur);
    $("#creditCard").on("input", creditCardFormat);
    $("#xykNo").on("input", creditCardFormat);
    $("#xykNo").on("blur", infoInputBlur);
    $userId.on("input", userIdFormat);
    $userPhone.on("input", userPhoneFormat);
    $("#dateInput").on("input", dateFormat);
    $("#cvn2").on("input", numberFormat);
    $("#verify-code").on("input", numberFormat);
    $("#resetInfo").on("click", resetInput);
    $("#link-mall").on("click", function() {
        location.href = returnUrl;
    });
    $("#guidance-code").hover(function() {
        $("#payCode .modal-body>table").hide();
        $("#payCode .modal-body>ol").show();
    }, function() {
        $("#payCode .modal-body>ol").hide();
        $("#payCode .modal-body>table").show();
    });

    $("#close-paycode").on("click", function() {
        $(this).hide();
        // $("#payCode .modal-content").hide(1000);
        $("#payCode .modal-content").animate({
                'width':0,

            },1010);

        $("#left_code_box").animate({
                'width':295,

            },1010);
        setTimeout(function() {
            $('#payCode').modal('hide');
        }, 1000);

    });

    $("#left_code").on("click",function  () {
        $('#payCode').modal('show');
        $("#payCode .modal-content").animate({
                'width':380,

            },1010);
        $("#left_code_box").animate({
                'width':0,

            },1010);
        setTimeout(function() {
            $("#close-paycode").show();
        }, 1000);
        
    });
    $(".check_label").on("click", function() {
        if ($("#agreeInput").attr("checked")) {
            $("#agreeInput").removeAttr("checked");
        } else {
            $("#agreeInput").attr("checked", true);
        }
        setAgreeDate()
    });
    setAgreeDate()
}

module.exports = {
    setOrderInfo: setOrderInfo,
    setSelect: setSelect,
    setRate: setRate,
    initView: initView,
    toResult: toResult,
    setReadOnly: setReadOnly,
    getVerifyCode: getVerifyCode,
    countDownTime: countDownTime,
    toFillUserInfo: toFillUserInfo,
    canGetCode:canGetCode
};